package com.dongnam.quanly.common.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.common.model.TonKho;
import com.dongnam.quanly.common.model.VatTuHangHoa;
import com.dongnam.quanly.common.model.enumtype.TrangThaiDonHang;
import com.dongnam.quanly.common.model.enumtype.TrangThaiTonKho;
import com.dongnam.quanly.common.persistence.HibernateUtil;

public class TonKhoDao extends ExtendedGenericDao<TonKho, String> {

	private static final Logger logger = LoggerFactory.getLogger(TonKhoDao.class);

	public long findCountByFilters() {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		return ((Number) crit.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	}

	@SuppressWarnings("unchecked")
	public List<TonKho> findByFilters(int pageSize, int pageNumber, String sortField, String sortOrder) {

		Criteria crit = getSession().createCriteria(getPersistentClass());

		crit.setFirstResult(pageNumber * pageSize);
		crit.setMaxResults(pageSize);

		crit.setFirstResult(pageNumber * pageSize);
		crit.setMaxResults(pageSize);
		if (sortOrder != null && !sortOrder.equalsIgnoreCase("UNSORTED") && sortField != null) {
			if (sortOrder.equalsIgnoreCase("ASCENDING")) {
				crit.addOrder(Order.asc(sortField));
			} else {
				crit.addOrder(Order.desc(sortField));
			}
		}
		return crit.list();
	}

	public List<TonKho> listTonKhoByPhieuNhap(String sophieu) {

		String queryString = "Select tonkho from TonKho tonkho" + " where tonkho.phieuNhapKho=:sophieu";
		Query query = getSession().createQuery(queryString);

		query.setParameter("sophieu", sophieu);

		@SuppressWarnings("unchecked")
		List<TonKho> list = query.list();

		return list;

	}

	public List<TonKho> listTonKhoByPhieuXuat(String sophieu) {

		String queryString = "Select tonkho from TonKho tonkho" + " where tonkho.phieuXuatKho=:sophieu";
		Query query = getSession().createQuery(queryString);

		query.setParameter("sophieu", sophieu);

		@SuppressWarnings("unchecked")
		List<TonKho> list = query.list();

		return list;

	}

	public List<TonKho> listTonKhoByMaVthh(String mavthh) {
		String queryString = "Select tonkho from TonKho tonkho"
				+ " where tonkho.vatTuHangHoa=:mavthh and tonkho.trangThai=:trangthai and tonkho.lock=:lock";
		Query query = getSession().createQuery(queryString);

		query.setParameter("mavthh", mavthh);
		query.setParameter("trangthai", TrangThaiTonKho.TRONGKHO);
		query.setParameter("lock", false);

		@SuppressWarnings("unchecked")
		List<TonKho> list = query.list();

		return list;
	}

}
